<script setup lang="ts">
import { h } from "vue";
import { useRoute } from "vue-router";
import { Plus } from "@element-plus/icons-vue";
import { ElButton, ElMessage, ElSwitch } from "element-plus";

import StallModify from "./components/StallModify.vue";

import ApiActivity from "@/api/activity";
import useModal from "@/hooks/useModal";
import useRequest from "@/hooks/useRequest";
import useProTable from "@/hooks/useProTable";

import { TStall } from "@/global";

const { params } = useRoute();
const act_id = +params.id;

//  v展位名称、示意图「非必填」、描述、备注、押金金额、展位显示状态「显示/隐藏」
const tableColumns = [
  {
    label: "序号",
    type: "index",
    width: 70,
  },
  // {
  //     label: "示例图",
  //     slot: "cover"
  // },
  {
    label: "展位名称",
    prop: "stand_title",
  },
  {
    label: "押金（元）",
    prop: "deposit_amount",
    width: 120,
    render: (data: any) => data.deposit_amount / 100,
  },
  {
    label: "状态",
    slot: "is_show",
    width: 100,
  },
  {
    label: "排序",
    prop: "sort",
    width: 100,
  },
  {
    label: "详情",
    prop: "stand_desc",
    width: "300",
    showOverflowTooltip: true,
  },
  {
    label: "备注",
    prop: "stand_notes",
  },
  {
    label: "操作",

    width: 150,
    slot: ({ row }: any) =>
      h(
        ElButton,
        {
          text: true,
          onClick: () => open(row),
        },
        "编辑"
      ),
  },
];

const changeSwitch = (row: TStall) => {
  const is_show = row.is_show ? 0 : 1;
  // runStallEdit({ ...row, is_show });
  row.is_show = is_show;
  runStallEdit(row);
};

const [ProTable, { tableApi }] = useProTable({
  fetchUrl: ApiActivity.standList,
  fetchOptions: {
    defaultSearch: { act_id },
  },
  tableOptions: {
    columns: tableColumns,
  },
});

const [Modal, { open, close }] = useModal({
  width: 500,
  title: (source) => (source ? "编辑展位" : "新增展位"),
});

// 编辑/创建成功
const handleSuccess = () => {
  // 关闭弹窗
  close();
  tableApi.refresh();
};

// 快速编辑状态
const {
  isFetching: loadingEdit,
  lastParams,
  run: runStallEdit,
  onFetchResponse,
  onFetchError,
} = useRequest(ApiActivity.standEdit, {
  immediate: false,
});

// 编辑成功
onFetchResponse(() => {
  ElMessage.success("编辑成功！");
});

// 编辑失败
onFetchError(() => {
  ElMessage.error("编辑失败！");
  const rowValue = lastParams.value.is_show ? 0 : 1;
  lastParams.value.is_show = rowValue;
});
</script>

<template>
  <ProTable>
    <template #tool-left>
      <ElButton type="primary" size="large" :icon="Plus" @click="open()"
        >新增展位
      </ElButton>
    </template>

    <template #table-is_show="{ row }">
      <ElSwitch
        :model-value="row.is_show"
        inline-prompt
        :active-value="0"
        :inactive-value="1"
        :loading="loadingEdit && lastParams?.id == row.id"
        active-text="显示"
        inactive-text="隐藏"
        @click="changeSwitch(row)"
      />
    </template>
  </ProTable>

  <Modal>
    <StallModify :actId="act_id" @success="handleSuccess" />
  </Modal>
</template>
